/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.wizards.template;

import cn.easyplatform.entities.beans.page.PageBean;
import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.lang.Nums;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.GridEditorCallback;
import cn.easyplatform.studio.web.editors.TableInfo;
import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import cn.easyplatform.studio.web.editors.support.ZulXsdUtil;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.apache.commons.lang3.math.NumberUtils;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;
import org.zkoss.zul.impl.InputElement;
import org.zkoss.zul.impl.XulElement;

import java.util.Iterator;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class Page0 extends AbstractTemplate {

    protected Intbox cols;

    protected TableInfo mainTable;

    private Radiogroup toolbar;

    protected Grid canvas;

    @Override
    protected void initComponents(Component root) {
        for (Component c : root.getFellows()) {
            if (c.getId().equals("page_intbox_cols")) {
                cols = (Intbox) c;
                cols.addEventListener(Events.ON_CHANGE, this);
            } else if (c instanceof A || c instanceof Button) {
                c.addEventListener(Events.ON_CLICK, this);
            } else if (c.getId().equals("page_grid_canvas")) {
                canvas = (Grid) c;
                canvas.addEventListener(Events.ON_CHANGE, this);
            } else if (c.getId().equals("page_radiogroup_toolbar")) {
                toolbar = (Radiogroup) c;
            }
        }
        createColumns();
    }

    private void createColumns() {
        for (int i = 0; i < cols.getValue(); i++) {
            Column col = new Column();
            Textbox txt = new Textbox("0");
            txt.setTooltiptext(Labels.getLabel("wizard.width"));
            txt.addEventListener(Events.ON_CHANGE, this);
            txt.setHflex("1");
            col.appendChild(txt);
            Combobox cbx = new Combobox();
            cbx.appendChild(new Comboitem("left"));
            cbx.appendChild(new Comboitem("center"));
            cbx.appendChild(new Comboitem("right"));
            cbx.setTooltiptext(Labels.getLabel("wizard.align"));
            cbx.addEventListener(Events.ON_CHANGE, this);
            cbx.setReadonly(true);
            cbx.setSelectedIndex(0);
            cbx.setHflex("1");
            col.appendChild(cbx);
            canvas.getColumns().appendChild(col);
        }
    }

    @Override
    protected void dispatch(Event evt) {
        Component c = evt.getTarget();
        if (c == canvas) {
            mainTable = (TableInfo) evt.getData();
            canvas.getRows().getChildren().clear();
            redraw();
        } else if (c.getId().equals("page_button_table")) {
            AbstractView.createTableView(
                    new GridEditorCallback(canvas,
                            Labels.getLabel("wizard.table")), true, evt.getTarget())
                    .doOverlapped("right,center");
        } else if (c == cols) {
            canvas.getColumns().getChildren().clear();
            canvas.getRows().getChildren().clear();
            createColumns();
            redraw();
        } else if (c.getParent() instanceof Column) {
            setColumnProperty(c);
        }
    }

    private void setColumnProperty(Component c) {
        Column col = (Column) c.getParent();
        if (c instanceof Combobox) {
            col.setAlign(((Combobox) c).getSelectedItem().getLabel());
        } else {
            Textbox tbx = (Textbox) c;
            if (!Strings.isBlank(tbx.getValue())) {
                int width = Nums.toInt(tbx.getValue(), 0);
                if (width > 0)
                    col.setWidth(width + "px");
                else
                    col.setWidth(tbx.getValue());
            } else {
                col.setWidth(null);
            }
        }
        col.invalidate();
    }

    private void redraw() {
        if (mainTable == null)
            return;
        Iterator<TableField> itr = mainTable.getFields().iterator();
        while (itr.hasNext()) {
            Row row = new Row();
            for (int i = 0; i < cols.getValue(); i++) {
                if (itr.hasNext()) {
                    TableField tf = itr.next();
                    row.appendChild(new Label(tf.getDescription()));
                    if (row.getChildren().size() == cols.getValue()) {
                        canvas.getRows().appendChild(row);
                        row = new Row();
                    }
                    XulElement input = WebUtils.createComponent(tf);
                    if (input instanceof InputElement&&!(input instanceof Datebox)&&!(input instanceof Timebox)){
                        ((InputElement) input).setPlaceholder(Labels.getLabel("dic.placeholder.input"));
                    }
                    input.setTooltiptext(tf.getName());
                    input.setHflex("1");
                    row.appendChild(input);
                    if (row.getChildren().size() == cols.getValue()) {
                        canvas.getRows().appendChild(row);
                        row = new Row();
                    }
                } else {
                    canvas.getRows().appendChild(row);
                    break;
                }
            }
        }
    }

    protected String getContent() {
        StringBuilder sb = new StringBuilder();
        sb.append("<grid")
                .append(" sclass=\"noborder\" oddRowSclass=\"none\" hflex=\"1\"")
                .append(" vflex=\"1\">").append("<columns>");
        for (Component c : canvas.getColumns().getChildren()) {
            sb.append("<column ");
            String width = ((Textbox) c.getFirstChild()).getValue().trim();
            if (!width.equals("") && !width.equals("0")) {
                sb.append("width=\"").append(width);
                if (NumberUtils.isNumber(width))
                    sb.append("px");
                sb.append("\"");
            }
            String align = ((Combobox) c.getLastChild()).getSelectedItem()
                    .getLabel();
            if (!align.equals("left"))
                sb.append(" align=\"").append(align).append("\"");
            sb.append("/>");
        }
        sb.append("</columns>");
        sb.append("<rows>");
        String value = toolbar.getSelectedItem().getValue();
        String[] pos = null;
        if (!value.equals("")) {
            pos = value.split(",");
            if (pos[0].equals("top"))
                buildToolbar(sb, pos[1]);
        }
        if (!canvas.getRows().getChildren().isEmpty()) {
            for (Component row : canvas.getRows().getChildren()) {
                sb.append("<row>");
                for (Component c : row.getChildren()) {
                    if (c instanceof InputElement) {
                        InputElement inputElement = (InputElement) c;
                        if (!Strings.isBlank(inputElement.getText())&&!(inputElement instanceof Datebox)&&!(inputElement instanceof Timebox))
                            sb.append("<").append("combobox query=\"select detailno,#726 from sys_dic_detail_info where diccode='"+inputElement.getText()+"'\"");
                        else
                            sb.append("<").append(c.getDefinition().getName());
                    } else
                        sb.append("<").append(c.getDefinition().getName());
                    if (c instanceof Label)
                        sb.append(" value=\"").append(((Label) c).getValue())
                                .append("\"");
                    else
                        sb.append(" id=\"#{")
                                .append(((XulElement) c).getTooltiptext())
                                .append("}\" ").append(" hflex=\"1\"");
                    sb.append("/>");
                }
                sb.append("</row>");
            }
        }
        if (pos != null && pos.length == 2 && pos[0].equals("bottom"))
            buildToolbar(sb, pos[1]);
        sb.append("</rows>");
        sb.append("</grid>");
        return CodeFormatter.formatXML(ZulXsdUtil.buildDocument(sb
                .toString()));
    }

    @Override
    public PageBean getEntity() {
        PageBean pb = new PageBean();
        if (canvas.getRows().getChildren().isEmpty() == false)
            pb.setTable(mainTable.getTable());
        pb.setAjax(getContent());
        return pb;
    }

    protected void buildToolbar(StringBuilder sb, String align) {
        sb.append("<row").append(" spans=\"").append(cols.getValue())
                .append("\"");
        if (align.equals("center"))
            sb.append(" align=\"center\"");
        else if (align.equals("right"))
            sb.append(" align=\"right\"");
        sb.append(">").append("<div>");
        sb.append("<button label=\"").append(Labels.getLabel("button.add"))
                .append("\" event=\"create()\"")
                .append(" iconSclass=\"z-icon-plus\"/>");
        sb.append("<button label=\"").append(Labels.getLabel("button.delete"))
                .append("\" event=\"remove()\"")
                .append(" iconSclass=\"z-icon-minus\"/>");
        sb.append("<button label=\"").append(Labels.getLabel("button.save"))
                .append("\" event=\"save()\"")
                .append(" iconSclass=\"z-icon-save\"/>");
        sb.append("</div>").append("</row>");
    }
}
